{% extends 'dashboard/base.html' %}

{% block title %}订单管理 - 巧巧点餐管理后台{% endblock %}

{% block content %}
<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">订单管理</h1>
    <div>
        <a href="{% url 'dashboard:order_export' %}{% if request.GET %}?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}{% endif %}" class="btn btn-sm btn-success shadow-sm">
            <i class="fas fa-download fa-sm text-white-50"></i> 导出CSV
        </a>
    </div>
</div>

<!-- 数据卡片 -->
<div class="row">
    <!-- 今日订单 -->
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">今日订单</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ today_orders_count }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-calendar-day fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 今日销售额 -->
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">今日销售额</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ today_sales }} 亲亲币</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-coins fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 待处理订单 -->
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">待处理订单</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ pending_orders }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-hourglass-half fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 订单完成率 -->
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">订单完成率</div>
                        <div class="row no-gutters align-items-center">
                            <div class="col-auto">
                                <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">{{ completed_rate }}%</div>
                            </div>
                            <div class="col">
                                <div class="progress progress-sm mr-2">
                                    <div class="progress-bar bg-info" role="progressbar" style="width: {{ completed_rate }}%" aria-valuenow="{{ completed_rate }}" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-clipboard-check fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">筛选条件</h6>
    </div>
    <div class="card-body">
        <!-- 搜索和筛选 -->
        <form method="get" class="search-form">
            <div class="row">
                <div class="col-md-3 mb-2">
                    <div class="form-group mb-2">
                        <label for="search" class="small">订单号/桌号/用户</label>
                        <input type="text" id="search" name="search" class="form-control" value="{{ search }}" placeholder="搜索订单号、桌号、用户...">
                    </div>
                </div>
                <div class="col-md-3 mb-2">
                    <div class="form-group mb-2">
                        <label for="status" class="small">订单状态</label>
                        <select id="status" name="status" class="form-control">
                            <option value="">全部状态</option>
                            <option value="1" {% if status == '1' %}selected{% endif %}>待确认</option>
                            <option value="2,3" {% if status == '2,3' %}selected{% endif %}>制作中</option>
                            <option value="4,5" {% if status == '4,5' %}selected{% endif %}>已完成</option>
                            <option value="6" {% if status == '6' %}selected{% endif %}>已取消</option>
                        </select>
                    </div>
                </div>
                <div class="col-md-3 mb-2">
                    <div class="form-group mb-2">
                        <label for="date_from" class="small">开始日期</label>
                        <input type="date" id="date_from" name="date_from" class="form-control" value="{{ date_from }}">
                    </div>
                </div>
                <div class="col-md-3 mb-2">
                    <div class="form-group mb-2">
                        <label for="date_to" class="small">结束日期</label>
                        <input type="date" id="date_to" name="date_to" class="form-control" value="{{ date_to }}">
                    </div>
                </div>
                <div class="col-12 mb-2 d-flex justify-content-end">
                    <div class="form-group mb-2 d-flex">
                        <button type="submit" class="btn btn-primary btn-sm mr-2">
                            <i class="fas fa-search fa-sm"></i> 搜索
                        </button>
                        <a href="{% url 'dashboard:order_list' %}" class="btn btn-light btn-sm">
                            <i class="fas fa-redo fa-sm"></i> 重置
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 订单列表 -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-sm-flex align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">订单列表</h6>
        <!-- 批量操作按钮 -->
        <div class="dropdown">
            <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" id="bulkActionDropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                批量操作
            </button>
            <div class="dropdown-menu" aria-labelledby="bulkActionDropdown">
                <form id="batchActionForm" method="post" action="{% url 'dashboard:order_batch_action' %}">
                    {% csrf_token %}
                    <input type="hidden" id="batchAction" name="action" value="">
                    <div id="selectedOrderIds"></div>
                    <button type="button" class="dropdown-item batch-action" data-action="mark_paid">确认订单(开始制作)</button>
                    <button type="button" class="dropdown-item batch-action" data-action="mark_delivered">标记为制作完成</button>
                    <button type="button" class="dropdown-item batch-action" data-action="mark_received">标记为已送达</button>
                    <button type="button" class="dropdown-item batch-action" data-action="mark_completed">标记为已完成</button>
                    <div class="dropdown-divider"></div>
                    <button type="button" class="dropdown-item batch-action text-danger" data-action="mark_cancelled">标记为已取消</button>
                </form>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-hover" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th width="3%">
                            <div class="custom-control custom-checkbox">
                                <input type="checkbox" class="custom-control-input" id="selectAll">
                                <label class="custom-control-label" for="selectAll"></label>
                            </div>
                        </th>
                        <th width="10%">订单号</th>
                        <th width="10%">用户</th>
                        <th width="10%">桌号/收件人</th>
                        <th width="15%">下单时间</th>
                        <th width="8%">金额</th>
                        <th width="10%">状态</th>
                        <th width="14%">备注</th>
                        <th width="20%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% if orders %}
                        {% for order in orders %}
                        <tr>
                            <td>
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input order-checkbox" id="order{{ order.id }}" value="{{ order.id }}">
                                    <label class="custom-control-label" for="order{{ order.id }}"></label>
                                </div>
                            </td>
                            <td>{{ order.order_number }}</td>
                            <td>{{ order.user.username }}</td>
                            <td>
                                {% if order.table_number %}
                                    <span class="d-block">桌号: {{ order.table_number }}</span>
                                {% endif %}
                                {% if order.receiver %}
                                    <span class="d-block small">{{ order.receiver }}</span>
                                    {% if order.receiver_phone %}
                                        <span class="d-block small text-muted">{{ order.receiver_phone }}</span>
                                    {% endif %}
                                {% endif %}
                            </td>
                            <td>{{ order.created_at|date:"Y-m-d H:i:s" }}</td>
                            <td>{{ order.total_price }} 币</td>
                            <td>
                                {% if order.status == 1 %}
                                    <span class="badge badge-warning">待确认</span>
                                {% elif order.status == 2 %}
                                    <span class="badge badge-info">制作中(已付款)</span>
                                {% elif order.status == 3 %}
                                    <span class="badge badge-primary">制作中(已发货)</span>
                                {% elif order.status == 4 %}
                                    <span class="badge badge-success">已完成(已收货)</span>
                                {% elif order.status == 5 %}
                                    <span class="badge badge-success">已完成(已评价)</span>
                                {% elif order.status == 6 %}
                                    <span class="badge badge-danger">已取消</span>
                                {% else %}
                                    <span class="badge badge-secondary">未知</span>
                                {% endif %}
                            </td>
                            <td class="text-truncate" style="max-width: 150px;">{{ order.remark|default:'无备注'|truncatechars:50 }}</td>
                            <td>
                                <div class="btn-group">
                                    <a href="{% url 'dashboard:order_detail' order_id=order.id %}" class="btn btn-info btn-sm">
                                        <i class="fas fa-eye fa-sm"></i> 查看
                                    </a>
                                    <a href="{% url 'dashboard:order_print' order_id=order.id %}" target="_blank" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-print fa-sm"></i> 打印
                                    </a>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                            <i class="fas fa-cog fa-sm"></i>
                                        </button>
                                        <div class="dropdown-menu">
                                            {% if order.status == 1 %}
                                                <a class="dropdown-item" href="{% url 'dashboard:order_update_status_direct' order_id=order.id status=2 %}">
                                                    <i class="fas fa-credit-card fa-sm text-info"></i> 确认订单(开始制作)
                                                </a>
                                                <a class="dropdown-item text-danger cancel-btn" href="#" data-toggle="modal" data-target="#cancelModal" data-id="{{ order.id }}" data-number="{{ order.order_number }}">
                                                    <i class="fas fa-times fa-sm"></i> 取消订单
                                                </a>
                                            {% elif order.status == 2 %}
                                                <a class="dropdown-item" href="{% url 'dashboard:order_update_status_direct' order_id=order.id status=3 %}">
                                                    <i class="fas fa-shipping-fast fa-sm text-warning"></i> 标记为制作完成
                                                </a>
                                            {% elif order.status == 3 %}
                                                <a class="dropdown-item" href="{% url 'dashboard:order_update_status_direct' order_id=order.id status=4 %}">
                                                    <i class="fas fa-box-open fa-sm text-primary"></i> 标记为已送达
                                                </a>
                                            {% elif order.status == 4 %}
                                                <a class="dropdown-item" href="{% url 'dashboard:order_update_status_direct' order_id=order.id status=5 %}">
                                                    <i class="fas fa-check-circle fa-sm text-success"></i> 标记为已完成
                                                </a>
                                            {% endif %}
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    {% else %}
                        <tr>
                            <td colspan="9" class="text-center py-4">暂无订单数据</td>
                        </tr>
                    {% endif %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        {% if orders.has_other_pages %}
        <div class="mt-4">
            <nav aria-label="分页导航">
                <ul class="pagination justify-content-center">
                    {% if orders.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ orders.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="上一页">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link" aria-hidden="true">&laquo;</span>
                    </li>
                    {% endif %}

                    {% for i in orders.paginator.page_range %}
                        {% if orders.number == i %}
                        <li class="page-item active">
                            <span class="page-link">{{ i }}</span>
                        </li>
                        {% elif i > orders.number|add:'-3' and i < orders.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ i }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">{{ i }}</a>
                        </li>
                        {% endif %}
                    {% endfor %}

                    {% if orders.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ orders.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}" aria-label="下一页">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    {% else %}
                    <li class="page-item disabled">
                        <span class="page-link" aria-hidden="true">&raquo;</span>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
        {% endif %}
    </div>
</div>

<!-- 取消订单确认模态框 -->
<div class="modal fade" id="cancelModal" tabindex="-1" role="dialog" aria-labelledby="cancelModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="cancelModalLabel">确认取消订单</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>您确定要取消订单 <strong id="orderNumber"></strong> 吗？</p>
                <p class="text-danger"><i class="fas fa-exclamation-triangle mr-1"></i> 取消后无法恢复，请谨慎操作。</p>
                <div class="form-group">
                    <label for="cancel_reason">取消原因：</label>
                    <textarea id="cancel_reason" name="note" class="form-control" rows="3" placeholder="请输入取消原因..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <form id="cancelForm" method="post" action="">
                    {% csrf_token %}
                    <input type="hidden" name="status" value="6">
                    <input type="hidden" id="cancel_note" name="note" value="">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="submit" class="btn btn-danger">确认取消</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 取消订单确认
        $('#cancelModal').on('show.bs.modal', function (event) {
            const button = $(event.relatedTarget);
            const orderId = button.data('id');
            const orderNumber = button.data('number');
            
            $('#orderNumber').text(orderNumber);
            $('#cancelForm').attr('action', '{% url "dashboard:order_update_status" order_id=0 %}'.replace('0', orderId));
            
            // 重置取消原因
            $('#cancel_reason').val('');
        });
        
        // 确认取消时同步取消原因到表单
        $('#cancelForm').on('submit', function() {
            $('#cancel_note').val($('#cancel_reason').val());
        });
        
        // 全选/取消全选
        $('#selectAll').change(function() {
            $('.order-checkbox').prop('checked', $(this).prop('checked'));
        });
        
        // 单个checkbox改变时，检查是否需要改变全选状态
        $('.order-checkbox').change(function() {
            if ($('.order-checkbox:checked').length === $('.order-checkbox').length) {
                $('#selectAll').prop('checked', true);
            } else {
                $('#selectAll').prop('checked', false);
            }
        });
        
        // 批量操作
        $('.batch-action').click(function() {
            const action = $(this).data('action');
            const checkedOrders = $('.order-checkbox:checked');
            
            if (checkedOrders.length === 0) {
                alert('请至少选择一个订单进行操作');
                return;
            }
            
            // 设置操作类型
            $('#batchAction').val(action);
            
            // 创建选中的订单ID的隐藏输入
            $('#selectedOrderIds').empty();
            checkedOrders.each(function() {
                const orderId = $(this).val();
                $('#selectedOrderIds').append('<input type="hidden" name="order_ids" value="' + orderId + '">');
            });
            
            // 确认操作
            const actionText = $(this).text();
            if (confirm('确定要将选中的 ' + checkedOrders.length + ' 个订单' + actionText + '吗？')) {
                $('#batchActionForm').submit();
            }
        });
    });
</script>
{% endblock %} 